package com.dly.blog.service.impl;

import cn.hutool.core.lang.UUID;
import com.dly.blog.domain.dto.FlySendDto;
import com.dly.blog.domain.dto.MessageContentDto;
import com.dly.blog.domain.enums.ChatType;
import com.dly.blog.properties.ChatProperties;
import com.dly.blog.service.ChatProxy;
import com.dly.blog.utile.JsonUtils;
import com.dly.blog.utile.SecurityUtils;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import okhttp3.HttpUrl;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient;
import reactor.core.publisher.Flux;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;

@Service
@ConditionalOnProperty(name = "blog.chat.fly.enable", havingValue = "true")
@AllArgsConstructor
public class FlyChatProxy implements ChatProxy {

    private final ChatProperties chatProperties;

    private final ExecutorService makePool;

    @Override
    public boolean matching(ChatType chatType) {
        return chatType.equals(ChatType.FLY);
    }

    @SneakyThrows
    @Override
    public Flux<String> send(List<MessageContentDto> messages) {
        String authUrl = getAuthUrl("https://spark-api.xf-yun.com/v1.1/chat", chatProperties.getFLy().getApiKey(), chatProperties.getFLy().getApiSecret());
        String url = authUrl.replace("http://", "ws://").replace("https://", "wss://");
        ReactorNettyWebSocketClient client = new ReactorNettyWebSocketClient();
        return Flux.create(fluxSink ->
                        makePool.execute(()-> client.execute(URI.create(url), session -> session
                                .send(Flux.just(session.textMessage(
                                        Objects.requireNonNull(JsonUtils.writeToJson(createFlySendDto(messages, chatProperties.getFLy().getAppId())))
                                )))
                                .thenMany(session.receive()
                                        .map(WebSocketMessage::getPayloadAsText)
                                        .doOnNext(fluxSink::next)).then()).block(Duration.ofSeconds(120))));
    }
    
    public FlySendDto createFlySendDto(List<MessageContentDto> messages, String appId){
        FlySendDto flySendDTO = new FlySendDto();
        flySendDTO.getHeader().setApp_id(appId);
        flySendDTO.getHeader().setUid("118143");
        flySendDTO.getPayload().getMessage().setText(messages);
        return flySendDTO;
    }
    

    public  String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";
        // System.err.println(preStr);
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // System.err.println(sha);
        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
                addQueryParameter("date", date).//
                addQueryParameter("host", url.getHost()).//
                build();

        // System.err.println(httpUrl.toString());
        return httpUrl.toString();
    }
}
